package library;

import java.sql.SQLException;
import java.util.List;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;

public class BookController {
	private static Dao<Book, String> bookDao;
	List<Book> result;
	int count;
	public BookController() throws SQLException{
		bookDao = DaoUtil.getDao(Book.class);
	}

    /**
     *  Search the book by keyword
     * @param keyword The word phase that want to getLibrarian
     * @return A Collection of Book that contain the keyword
     * @throws SQLException
     */
	public List<Book> search(String keyword) throws SQLException{
		if(result != null)
			result.clear();
		PreparedQuery<Book> preparedQuery = bookDao.queryBuilder().where().like("name", "%" + keyword + "%").prepare();
		result = bookDao.query(preparedQuery);
		count = result.size();
		return this.result;
	}
	
	public void updateStatus(Book book, BookStatus status) throws SQLException{
		Book objBook = bookDao.queryForSameId(book);
		objBook.setStatus(status);
		bookDao.update(objBook);
	}

   /**
     *  Find the book by id
     * @param id The book id that want to getLibrarian
     * @return A Book object
     * @throws Exception
     */
	public Book getBookById(int id) throws Exception{
		Book result = bookDao.queryForId(Integer.toString(id));
		if(result != null)
			return result;
		else
			throw new Exception("Book id: " + id + " not found.");
	}
	
	public Book getBookByName(String name) throws Exception{
		Book result = bookDao.queryForEq("name", name).get(0);
		if(result != null)
			return result;
		else
			throw new Exception("Book name: " + name + " not found.");
	}
	
	public boolean createNewBook(Book book) throws SQLException{
		return (bookDao.create(book) == 1);
	}

}
